<!--
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-08 08:35:19
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-26 14:30:33
 * @FilePath: \keep_motion_manger\src\components\importDialog\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-dialog :title="title" width="500px" :model-value="visible" destroy-on-close :before-close="beforeClose">
        <template #header>
            <span class="dialog-header">
                <el-button type="primary" :icon="Plus" @click="handleAdd" link :disabled="!canEdit"/>
            </span>
        </template>
        <el-form v-for="(dataItem, dataIndex) in editForms" :key="dataIndex" :inline="true" :model="dataItem" class="plural-form">
            <el-form-item :label="`第${ dataIndex + 1 }组`">
                <el-button type="danger" :icon="Delete" @click="handleDelete(dataIndex)" link size="small" :disabled="!canEdit"/>
            </el-form-item>
            <template v-for="(item, index) in editModule.filter(item => item.type !== 'forbidden')" :key="index">
                <el-form-item :label="item.label" class="form-item" :prop="item.vModel">
                    <el-input v-if="item.type === 'input'" v-model="dataItem[item.vModel]" :placeholder="item.placeholder" :disabled="item.forbidden || !canEdit" />

                    <el-switch v-else-if="item.type === 'switch'" v-model="dataItem[item.vModel]" :disabled="item.forbidden || !canEdit" />

                    <el-select v-else-if="item.type === 'select'" v-model="dataItem[item.vModel]" placeholder="请选择" clearable @change="changeSelect" :disabled="item.forbidden || !canEdit" >
                        <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                        />
                    </el-select>
                    <el-date-picker
                        v-else-if="item.type === 'date'"
                        v-model="dataItem[item.vModel]"
                        type="date"
                        placeholder="选择日期"
                        :disabled="item.forbidden || !canEdit" 
                    />
                    <el-upload
                        v-else-if="item.type === 'upload'"
                        class="avatar-uploader"
                        :action="`${baseUrl}${item.action(editModule[0].initialValue)}`"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess.bind(this, item.vModel, dataIndex)"
                        :before-upload="beforeAvatarUpload.bind(this, item.fileType)"
                        :disabled="item.forbidden || !canEdit"
                    >   
                        <div class="avatar-uploader-container" v-if="dataItem[item.vModel]">
                            <img v-if="!item.fileType" :src="`${baseUrl}${dataItem[item.vModel]}`" class="avatar" />
                            <video v-else-if="item.fileType === 'video'" controls :src="`${baseUrl}${dataItem[item.vModel]}`" class="avatar" />
                        </div>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="beforeClose">取消</el-button>
                <el-button type="primary" @click="handleSuccess" v-if="canEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>

import { ref, reactive, onMounted, defineProps, defineEmits, watch, computed } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue'


import { dictDataApi } from '@/api';
import './index.css';

const baseUrl = import.meta.env.VITE_BASE_URL;
const props = defineProps({
    visible: {
        type: Boolean,
        default: () => false
    },
    dialogType: {
        type: String,
        default: () => 'edit'
    },
    title: {
        type: String,
        default: () => '复数表格'
    },
    editData: {
        type: Object,
        default: () => ({})
    },
    editModule: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['close', 'successCallBack']);

const canEdit = computed(() => {
    return props.dialogType !== 'view';
});
const editForms = reactive([]);
const uploadHeaders = computed(() => {
    return {
        Authorization: sessionStorage.getItem("role") + ' ' + sessionStorage.getItem('token'),
    }
})



// 模拟根据 code 获取下拉框选项
const getOptions = async (code) => {
  // 这里可以根据 code 调用接口获取对应选项
  const res = await dictDataApi.getDictData({code});
  if (res.code === 200) return res.data.rows;
  return [];
};
// 初始化表单数据
const initForm = () => {
    for(let i = 0; i < props.editData.length; i++) {
        editForms[i] = reactive({});
        props.editModule.forEach(item => {
            editForms[i][item.vModel] = props.editData[i][item.vModel] !== undefined ? props.editData[i][item.vModel] : '';
        });
    }
};

// 新增
const handleAdd = () => {
    editForms.push(reactive({}));
    props.editModule.forEach(item => {
        editForms[editForms.length - 1][item.vModel] = item.initialValue !== undefined ? item.initialValue : '';
    });
}
const handleDelete = (index) => {
    editForms.splice(index, 1);
}

// 头像上传
const beforeAvatarUpload = (type = 'image', file) => {
    const allowHash = {
        image: ['image/jpeg', 'image/png', 'image/gif'],
        video: ['video/mp4', 'video/avi', 'video/mkv']
    }
    const tipsTextHash = {
        image: '图片',
        video: '视频'
    }
    const tipsTypeHash = {
        image: 'JPG, PNG, GIF',
        video: 'MP4, AVI, MKV'
    }
    const allowerList = allowHash[type];
    const isAllow = allowerList.includes(file.type);
    if (!isAllow) {
        ElMessage.error(`上传${tipsTextHash[type]}只能是 ${tipsTypeHash[type]} 格式!`);
    }
    return isAllow;
}
// 头像上传成功
const handleAvatarSuccess = (itemCode, dataIndex, res) => {
    editForms[dataIndex][itemCode] = res.data.file;
}

// 确定
const handleSuccess = async (res) => {
    const key = (props.editData[0] || {}).id ? (props.editData[0] || {}).id : props.editModule[0].vModel;
    emit('successCallBack', key, editForms);
};

// 关闭前
const beforeClose = (done) => {
    emit('close');
};

onMounted(async () => {
  // 先获取所有下拉框的选项
  const optionPromises = props.editModule
    .filter(item => item.type === 'select')
    .map(async (item) => {
      const options = await getOptions(item.optionsCode);
      item.options = options;
    });

  await Promise.all(optionPromises);
});

watch(() => props.visible, (newVal) => {
    if (newVal) {
        initForm();
        if(props.editData.length === 0) {
            handleAdd();
        }
    }
})
</script>